package com.zsule.controllers.front;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zsule.constants.CoreConstant;
import com.zsule.controllers.BaseController;
import com.zsule.controllers.websocket.UserLinkHandler;
import com.zsule.entity.ECartItem;
import com.zsule.entity.EOrder;
import com.zsule.entity.EOrderDetail;
import com.zsule.entity.EShop;
import com.zsule.entity.EUser;
import com.zsule.entity.EUserAddress;
import com.zsule.entity.Shipping;
import com.zsule.entity.ShopAndGoods;
import com.zsule.entity.req.ConfirmParam;
import com.zsule.service.ICartItemService;
import com.zsule.service.IOrderDetailService;
import com.zsule.service.IOrderService;
import com.zsule.service.IShopGoodsService;
import com.zsule.service.IShopService;
import com.zsule.service.IShoppingService;
import com.zsule.service.IUserAddressService;
import com.zsule.service.IUserService;

@Controller
public class EUserController extends BaseController {

	private static final Logger logger = Logger.getLogger(EUserController.class);
	
	@Autowired
	private IUserService euserService;
	@Autowired
	private IShopService eshopService;
	@Autowired
	private IShoppingService shippingService;
	@Autowired
	private IShopGoodsService shopAndGoodsService;
	@Autowired
	private ICartItemService ecartItemService;
	@Autowired
	private IUserAddressService euserAddressService;
	@Autowired
	private IOrderService eorderService;
	@Autowired
	private IOrderDetailService eorderDetailService;


	@Bean
	public UserLinkHandler userLinkHandler() {
		return new UserLinkHandler();
	}

	@ResponseBody
	@RequestMapping(value = "/euser/getByUserName", method = RequestMethod.POST)
	public EUser getByUserName(EUser euser, HttpServletRequest request) {
		return euserService.getByUserName(euser);
	}

	@ResponseBody
	@RequestMapping(value = "/euser/getByEmail", method = RequestMethod.POST)
	public EUser getByEmail(EUser euser, HttpServletRequest request) {
		return euserService.getByEmail(euser);
	}

	@ResponseBody
	@RequestMapping(value = "/euser/getByMobile", method = RequestMethod.POST)
	public EUser getByMobile(EUser euser, HttpServletRequest request) {
		return euserService.getByMobile(euser);
	}
	
	/*@ResponseBody
	@RequestMapping(value = "/euser/getByDomain", method = RequestMethod.POST)
	public EUser getByDomain(EShop eshop, HttpServletRequest request) {
		return eshopService.getByDomain(eshop.getDomainName());
	}*/

	@RequestMapping("/order/sub")
	public ModelAndView subCart(String shopId, HttpServletRequest request,
			String adsId) {
		ModelAndView mav = new ModelAndView("redirect:/bills");
		EUser user = (EUser) this.getSessionAttribute(request,
				CoreConstant.USER_SESSION_NAME);
		if (user == null) {
			mav.setViewName("redirect:/login");
			return mav;
		}
		EUserAddress euserAddress = euserAddressService.getEUserAddressById(adsId);
		EShop eshop = eshopService.getEShopByUser(shopId);
		Double distance = this.distance(eshop.getLng(), eshop.getLat(),euserAddress.getLng(), euserAddress.getLat());// 商户和店铺的距离
		List<Shipping> sps = shippingService.getShippingByUser(shopId);
		Shipping shipping = null;
		List<ECartItem> cartItems = ecartItemService.getSubItems(user.getId(),shopId);
		for (Shipping sp : sps) {
			if (sp.getRange() > distance) {
				continue;
			} else {
				shipping = sp;
				break;
			}
		}
		Double totalPrice = 0.0;
		EOrder order = new EOrder();
		String orderId = UUID.randomUUID().toString();
		order.setId(orderId);
		order.setOrderNumber(System.currentTimeMillis()+(int)Math.random()*99+"");
		order.setUserId(user.getId());
		order.setOrderTime(new Date());
		order.setShopperId(eshop.getUserId());
		order.setShopName(eshop.getShopName());
		order.setShopAddress(eshop.getShopAddress());
		order.setStatus(0);
		order.setOrderAddress(euserAddress.getAddress());
		order.setOrderReceiver(euserAddress.getReceiver());
		order.setReceiverMobile(euserAddress.getMobile());
		order.setUserLng(euserAddress.getLng());
		order.setUserLat(euserAddress.getLat());

		for (ECartItem item : cartItems) {
			EOrderDetail od = new EOrderDetail();
			od.setId(UUID.randomUUID().toString());
			od.setOrderId(order.getId());
			od.setOrderNumber(order.getOrderNumber());
			od.setGoodsId(item.getGoodsId());
			ShopAndGoods sad = shopAndGoodsService.findById(item.getGoodsId());
			od.setGoodsName(sad.getGoodsName());
			od.setOutPirce(sad.getOutPrice());
			od.setGoodsCount(item.getGoodsCount());
			od.setSubtotal(item.getGoodsCount() * sad.getOutPrice());
			totalPrice += od.getSubtotal();
//			eorderDetailService.save(od);
			eorderDetailService.insert(od);
			ecartItemService.remove(item);
		}
		if (shipping!=null&&shipping.getFreePrice() > totalPrice) {
			totalPrice += shipping.getShippingPrice();
		}
		order.setTotalPrice(totalPrice.doubleValue());
		eorderService.save(order);

		// 发送消息给对应商户，告诉商户，订单已经来到，是否接单
		try {
			userLinkHandler().sendOrderToShopper(shopId, "orderId:" + orderId);
		} catch (IOException e) {
			logger.error("OrderController.sendOrderToShopper", e);
		}
		return mav;
	}
	
	// 获取两个百度坐标点之间的距离
		private double distance(double centerLon, double centerLat,
				double targetLon, double targetLat) {
			double jl_jd = 102834.74258026089786013677476285;// 每经度单位米;
			double jl_wd = 111712.69150641055729984301412873;// 每纬度单位米;
			double b = Math.abs((centerLat - targetLat) * jl_jd);
			double a = Math.abs((centerLon - targetLon) * jl_wd);
			return Math.sqrt((a * a + b * b));
		}
		
		@ResponseBody
		@RequestMapping("/getConfirm")
		public Map<String, Object> getConfirm(HttpServletRequest request, ConfirmParam cparam) {
			Map<String, Object> returnMap = new HashMap<String, Object>();
			EUser user = (EUser) this.getSessionAttribute(request,
					CoreConstant.USER_SESSION_NAME);
			EUserAddress euserAddress = euserAddressService.getEUserAddressById(cparam.getAdsId());
			EShop eshop = eshopService.getEShopByUser(cparam.getShopId());
			Double distance = this.distance(eshop.getLng(), eshop.getLat(),euserAddress.getLng(), euserAddress.getLat());// 商户和店铺的距离
			List<Shipping> sps = shippingService.getShippingByUser(cparam.getShopId());
			Shipping shipping = null;
			List<ECartItem> cartItems = ecartItemService.getSubItems(user.getId(),cparam.getShopId());
			for (Shipping sp : sps) {
				if (sp.getRange() > distance) {
					continue;
				} else {
					shipping = sp;
					break;
				}
			}
			returnMap.put("address", euserAddress);
			returnMap.put("distance", distance);
			returnMap.put("shipping", shipping);
			returnMap.put("eshop", eshop);
			returnMap.put("ecartItems", cartItems);
			return returnMap;
		}
	
}
